//
// Created by wlk12 on 2024/3/3.
//

#pragma once
#include <iostream>
#include <vector>

struct TreeNode
{
    int value{};
    TreeNode* left{};
    TreeNode* right{};
    TreeNode() = default;
    explicit TreeNode(int value) : value(value) {}
    TreeNode(int value, TreeNode* l, TreeNode* r): value(value), left(l), right(r) {}
    TreeNode(TreeNode* l, TreeNode* r) : left(l), right(r) {}
};


void printTree(TreeNode* root, int level = 0)
{
    if (root != nullptr)
    {
        printTree(root->right, level + 1);
        for (int i = 0; i < level; ++i) {
            std::cout << "  ";
        }
        std::cout << root->value << std::endl;
        printTree(root->left, level + 1);
    }
}

TreeNode* createTree(const std::vector<int>& nums)
{
    if (nums.empty() || nums[0] < 0)
    {
        return nullptr;
    }
    std::vector<TreeNode*> nodes;
    nodes.resize(nums.size(), nullptr);
    nodes[0] = new TreeNode{nums[0]};
    for (int i = 1; i < nums.size(); ++i) {
        auto parent = nodes[(i-1)/2];
        if (nums[i] < 0 || parent == nullptr)
        {
            continue;
        }
        nodes[i] = new TreeNode{nums[i]};
        if (i%2 == 0)
        {
            parent->right = nodes[i];
        }
        else
        {
            parent->left = nodes[i];
        }
    }
    return nodes[0];
}

void deleteTree(TreeNode* root)
{
    if (root != nullptr)
    {
        deleteTree(root->left);
        deleteTree(root->right);
        delete root;
    }
}